package db

import (
	"database/sql"
	"fmt"
	"gitlab-dingtalk/server/config/logger"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Datasource struct {
	Type         string `yaml:"type"`
	Host         string `yaml:"host"`
	Port         string `yaml:"port"`
	Db           string `yaml:"db"`
	Username     string `yaml:"username"`
	Password     string `yaml:"password"`
	Dsn          string `yaml:"dsn"`
	MaxIdleConns int    `yaml:"maxIdleConns"`
	MaxOpenConns int    `yaml:"maxOpenConns"`
}

var (
	db    *gorm.DB
	sqlDB *sql.DB
)

func (config *Datasource) check() {
	if config.MaxIdleConns == 0 {
		config.MaxIdleConns = 10
	}
	if config.MaxOpenConns == 0 {
		config.MaxOpenConns = 20
	}
}
func InitDb(datasource *Datasource) error {
	datasource.check()
	config := &gorm.Config{}
	var dialector gorm.Dialector
	switch datasource.Type {
	case "mysql":
		dialector = initDbMysql(datasource)
	default:
		dialector = nil
	}
	dbOpen, err := gorm.Open(dialector, config)
	if err != nil {
		logger.Logger().Error(err.Error())
		return err
	}
	db = dbOpen
	if sqlDB, err = dbOpen.DB(); err != nil {
		logger.Logger().Error(err.Error())
		return err
	}

	sqlDB.SetMaxIdleConns(datasource.MaxIdleConns)
	sqlDB.SetMaxOpenConns(datasource.MaxOpenConns)
	return nil
}

func initDbMysql(datasource *Datasource) gorm.Dialector {
	if datasource.Dsn == "" {
		datasource.Dsn = fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
			datasource.Username, datasource.Password, datasource.Host, datasource.Port, datasource.Db)
	}
	return mysql.Open(datasource.Dsn)
}
func Db() *gorm.DB {
	return db
}

// 关闭连接
func CloseDB() {
	if sqlDB == nil {
		return
	}
	if err := sqlDB.Close(); nil != err {
		logger.Logger().Error(err.Error())
	}
}
